<?php

class User {

    var $username;
    var $password;

    function __construct() {

    }

    function login($username, $password) {
        global $db;
        $sql = 'SELECT * FROM users where username="'.$username.'"&&password="'.$password.'"';
        $rows= $db->query($sql, $fetchArray=true);
        if (count($rows)>0) return $rows[0]['id'];
        return null;
        
    }

    function get_user_info($user_id) {
        global $db;
        $sql = 'SELECT * FROM `users` WHERE `id`="'.$user_id.'"';
        $rows= $db->query($sql, $fetchArray=true);
        
        
        
        $sql = 'SELECT * FROM `sinhvien_info` WHERE `user_id`="'.$user_id.'"';
        $ext_rows = $db->query($sql, $fetchArray=true);
        if(count($ext_rows)>0){
            $rows[0]= array_merge($rows[0], $ext_rows[0]);
        }

        
        $sql = 'SELECT * FROM `giaovien_info` WHERE `user_id`="'.$user_id.'"';
        $ext_rows = $db->query($sql, $fetchArray=true);
        if(count($ext_rows)>0){
            $rows[0]= array_merge($rows[0], $ext_rows[0]);
        }

        if (count($rows)>0) return $rows[0];
        return null;
    }


    //Get USERS_LIST_TOTAL users from all users
    //for ex:
    //if USERS_LIST_TOTAL = 25 and $page_limit = 2
    //then we get the uses from 26 to 50
    function get_all_user_info($page_list){
        global $db;
        $start = USERS_LIST_TOTAL*($page_list-1);
        $sql = 'SELECT * FROM users ORDER BY username ASC limit '.$start.', '.USERS_LIST_TOTAL;
        $rows= $db->query($sql, $fetchArray=true);
        if (count($rows)>0) return $rows;
        return null;
    
    }

    function get_user_by_topic($topicId){
        global $db;
        $sql = 'SELECT * FROM sinhvien_info WHERE detai_id="'.$topicId.'"';
        $rows = $db->query($sql,$fetchArray = true);
        if (count($rows)>0) return $rows;
        return null;
    }

    function get_name_by_id($id){
        global $db;
        $sql = 'SELECT * FROM users WHERE id ="'.$id.'"';
        $rows = $db->query($sql,$fetchArray = true);
        if (count($rows)>0) return $rows[0]["displayname"];
        return null;
    }

    function get_group_name($group_id){
        global $db;
        $sql = 'SELECT * FROM usergroups where id="'.$group_id.'"';
        $rows= $db->query($sql, $fetchArray=true);
        if (count($rows)>0) return $rows[0]["groupname"];
        return null;
    }

    function get_display_name($id)
    {
        global $db;
        $sql = 'SELECT displayname FROM users WHERE `id`="'.$id.'"';
        $rows = $db->query($sql, $fetchArray=true);
        if (count($rows)>0){
            return $rows[0]["displayname"];
        }else{
            return null;
        }
    }

    function get_id_by_name($username){
        global $db;
        $sql = 'SELECT id FROM users WHERE `username`="'.$username.'"';
        $rows = $db->query($sql, $fetchArray=true);
        if (count($rows)>0){
            return $rows[0][0];
        }else{
            return null;
        }
    }

    function get_page_count(){
        global $db;
        $sql = 'SELECT count(*) FROM users';
        
        $rows= $db->query($sql, $fetchArray=true);
        if (count($rows)>0){
            if(intval($rows[0][0]/USERS_LIST_TOTAL)==$rows[0][0]/USERS_LIST_TOTAL){
                return intval($rows[0][0]/USERS_LIST_TOTAL);
            }else{
                return intval($rows[0][0]/USERS_LIST_TOTAL)+1;
            }
        }
        
        return null;
    }

    function name_exist($username, $except_id=0){
        global $db;
        $sql = "SELECT count(*) from users WHERE `username`='".$username."' && id!=".$except_id;
        $rows = $db->query($sql, $fetArray=true);
        $count = $rows[0][0];
        return $count;
       
    }

    function id_exist($user_id, $except_id=0){
        global $db;
        $sql = "SELECT count(*) from users WHERE `id`='".$user_id."' && id!=".$except_id;
        $rows = $db->query($sql, $fetArray=true);
        $count = $rows[0][0];
        return $count;
    }

    function add_new_user($username, $password, $password2, $displayname, $usergroups_id,
                            $adviser_info,
                            $diemhoctap, $diemrenluyen, $student_info){
        $check_reg = $this->check_register($username, $password, $password2, $usergroups_id);
        if ($check_reg!="OK"){
            throw new Exception($check_reg);
        }
        try{
            if ($this->name_exist($username)){
                throw new Exception("Username is exists!");
            }
            date_default_timezone_set('Asia/Krasnoyarsk');
            $join_date = date("Y-m-d");
            global $db;
            $sql = "INSERT INTO users (`username`, `password`, `displayname`, `join_date`, `usergroups_id`)
                    VALUES ('".$username."', '".$password."', '".$displayname."', '".$join_date."', '".$usergroups_id."' )";
            //echo $sql;

            $db->query($sql, $fetchArray=false);
            $user_id = $this->get_id_by_name($username);
            
            if ($user_id==NULL) throw new Exception("User not found!");
            
            switch($usergroups_id){
                case STUDENT_GROUP_ID:
                    $sql = "INSERT INTO sinhvien_info (`user_id`, `diemrenluyen`, `diemhoctap`, `sinhvien_info`)
                                VALUES('".$user_id."', '".$diemrenluyen."', '".$diemhoctap."', '".$student_info."')";
                    
                    break;
                case ADVISER_GROUP_ID:
                    $sql = "INSERT INTO giaovien_info (`user_id`, `giaovien_info`)
                                VALUES('".$user_id."', '".$adviser_info."')";
                    break;
                case ADMIN_GROUP_ID: default:
                    break;
            }

            $db->query($sql, $fetchArray=false);
            
       } catch (Exception $e) {
           throw $e;
        }
    }

    function check_group_id($groupid){
        return ($groupid==1 || $groupid==2 || $groupid==3);
    }

    function edit_exist_user($groupid,$user_id, $username, $displayname, $password, $password2, $usergroups_id,
            $adviser_info,
            $diemhoctap, $diemrenluyen, $student_info,$detai){
        $check_modify = $this->check_modify($username, $password, $password2, $usergroups_id);
        if ($check_modify!="OK"){
            throw new Exception($check_modify);
        }

        if (!($this->id_exist($user_id))){
            throw new Exception("User not found!");
        }
        //echo md5('');

        try{
            if ($this->name_exist($username, $except_id=$user_id)){
                throw new Exception("Username is exists!");
            }
            $join_date = date("Y-m-d");
            global $db;

            $sql = "UPDATE users 
                    SET `username`='".$username.
                        ($password!=null && $password!=md5('')?"',`password`='".$password:"").
                        "', `displayname`='".$displayname.
                        (have_permission($groupid==3)?
                        ($this->check_group_id($usergroups_id)?"',`usergroups_id`='".$usergroups_id:""):"").
                        "' WHERE id=".$user_id;
            $db->query($sql, $fetchArray=false);
    
            //echo $student_info."<br>";            

            if($this->check_group_id($usergroups_id)){
                $sql = "DELETE from giaovien_info WHERE user_id='".$user_id."'";
                $db->query($sql, $fetchArray=false);

                $sql = "DELETE from sinhvien_info WHERE user_id='".$user_id."'";
                $db->query($sql, $fetchArray=false);
                switch($usergroups_id){
                    case STUDENT_GROUP_ID:
                        $sql = "INSERT INTO sinhvien_info (`user_id`, `diemrenluyen`, `diemhoctap`, `sinhvien_info`,`detai_id`)
                                    VALUES('".$user_id."', '".$diemrenluyen."', '".$diemhoctap."', '".$student_info."','".$detai."')";

                        break;
                    case ADVISER_GROUP_ID:
                        $sql = "INSERT INTO giaovien_info (`user_id`, `giaovien_info`)
                                    VALUES('".$user_id."', '".$adviser_info."')";
                        break;
                    case ADMIN_GROUP_ID: default:
                        break;
                }
            }
            $db->query($sql, $fetchArray=false);

       } catch (Exception $e) {
           throw $e;
        }
    }
    // userId cua sinh vien
    function enroll_topic($topicId,$userId){
        global $db;
        try{
            global $db;
            $sql = "UPDATE sinhvien_info
                    SET `detai_id`='".$topicId.
                        "' WHERE user_id=".$userId;
            $db->query($sql, $fetchArray=false);
            $sql = "UPDATE detai SET `status` = 1 WHERE accept_student=".$userId;
            $db->query($sql, $fetchArray=false);
        } catch (Exception $e) {
           throw $e;
        }
    } 

    function check_topicid($userId,$topicId){
        global $db;
        $sql = 'SELECT * from sinhvien_info WHERE `user_id`='.$userId;
        $rows = $db->query($sql, $fetArray=true);
        $count = $rows[0]['detai_id'];                
        return $rows[0]['detai_id']!=$topicId;

    }
    function get_user_info_html($alt, $userinfo){
            global $page, $user, $template2;
            $xtpl = new XTemplate('users_info.html',PAGE_PATH.DS.DS.$page.DS.DS.'tpl');
            $html_class = "table_row_alt".$alt;
            $edit_img = LAYOUT_URL."/images/edit.png";
            $id=$userinfo["id"];
            $username=$userinfo["username"];
            $displayname=$userinfo["displayname"];
            $join_date=$userinfo["join_date"];
            $group = $user->get_group_name($userinfo["usergroups_id"]);
            $xtpl->assign('html_class', $html_class);
            $xtpl->assign('id', $id);
            $xtpl->assign('username', $username);
            $xtpl->assign('displayname', $displayname);
            $xtpl->assign('group', $group);
            $xtpl->assign('join_date', $join_date);
            $xtpl->assign('view', '<a href="'.ABS_URL.'?page=admin&act=viewuser&userid='.$id.'"><img style="margin: 4px; border:0" src="'.$edit_img.'"></a>');

            $xtpl->parse( 'user' );
            $user_content= $xtpl->text('user');
            return $user_content;
    }

    
    function create_group_dropbox(){
        global $db;
        $res = '<select name="group" id="group">';
        $sql = "SELECT * from usergroups ORDER BY id ASC";
        $rows= $db->query($sql, $fetchArray=true);
        for ($i=0; $i<count($rows); $i++){
            $res = $res.'<option value="'.$rows[$i][0].'">'.$rows[$i][1].'</option>';
        }
        return $res.'</select>';
    }
    

    function check_register($username, $password, $password2, $usergroups_id){
        $msg="OK";
        if ($username=="" || $password==""){
            $msg = "Username or password is null!";
        }

        if ($password != $password2){
            $msg = "Password does not match!";
        }

        if ($usergroups_id!=1 && $usergroups_id!=2 && $usergroups_id!=3){
            $msg = "No user group xx found!";
        }

        return $msg;
    }


    function check_modify($username, $password, $password2, $usergroups_id){
        
        if ($username==""){
            $msg = "Username is null!";
            return $msg;
        }

        if ($password != $password2){
            $msg = "Password does not match!";
            return $msg;
        }

        if ($usergroups_id!=0 && $usergroups_id!=1 && $usergroups_id!=2 && $usergroups_id!=3){
            $msg = "No user group found!";
            return $msg;
        }
        
        return "OK";
    }

    function delete_user($user_id){
        global $db;
        if (!($this->id_exist($user_id))){
            throw new Exception("User not found!");
        }

        try{
            if ($user_id==$_SESSION['id']){
                throw new Exception("Warning: You can't delete yourself!");
            }
            if (have_permission($groupid=3)){//Have admin permission
                $sql = "DELETE from users WHERE id='".$user_id."'";
                $db->query($sql, $fetchArray=false);
                
                $sql = "SELECT * from detai WHERE giaovien_id='".$user_id."'";               
                $rows = $db->query($sql, $fetArray=true);
                for ($i = 0; $i < count($rows); ++$i) {
                    $sql1 = "UPDATE sinhvien_info SET `detai_id`= 0 WHERE detai_id ='" .$rows[$i]['id']."'";
                    $db->query($sql1, $fetchArray=false);
                }
                
                $sql = "DELETE from detai WHERE giaovien_id='" . $user_id . "'";
                $db->query($sql, $fetchArray = false);
                
                $sql = "DELETE from giaovien_info WHERE user_id='".$user_id."'";
                $db->query($sql, $fetchArray=false);
                                
                $sql = "DELETE from sinhvien_info WHERE user_id='".$user_id."'";
                $db->query($sql, $fetchArray=false);
                
                return true; //DEL COMPLETED 
            }

        }catch(Exception $e){
            throw $e;
        }
    }

}


?>